<template>
	<view class="training">
		<view class="info-card">
			<view class="course-info">
				<view class="title">
					<text class="course-name">{{ data.courseTitle }}{{ data.teamName }}</text>
				</view>
				<view class="time-box">
					<template v-if="data.times && data.times.length > 0">
						<view class="time-box-item" v-for="(timeSlot, index) in data.times" :key="index">
							<view class="time-info-row">
								<text class="label">时间</text>
								<text class="value">
									{{ parseTime(timeSlot.startTime, '{y}-{m}-{d}') }} 
									{{ parseTime(timeSlot.startTime, '{h}:{i}') }}-{{ parseTime(timeSlot.endTime, '{h}:{i}') }}
								</text>
							</view>
							<view class="address-info-row" v-if="timeSlot.address && timeSlot.location" @click="handleNavigateToLocation(timeSlot)">
								<text class="label">培训地点</text>
								<text class="value address-link">{{ timeSlot.address }} (点击导航)</text>
							</view>
						</view>
					</template>
					<view class="time-box-item" v-else>
						<text class="label">培训时间</text>
						<text class="value">未安排</text>
					</view>
				</view>
			</view>

			<view class="user-info">
				<view class="student-info">
					<text class="subject">{{ data.title }}</text>
					<view class="info-item" style="display: flex;align-items: center;">
						<text class="label">姓名</text>
						<image class="avatar" v-if="userinfo.avatar" :src="userinfo.avatar" mode="aspectFill"></image>
						<text class="value">{{ userinfo.nickname }}</text>
					</view>
					<view class="info-item">
						<text class="label">手机号</text>
						<text class="value">{{ userinfo.phone }}</text>
					</view>
					<view class="info-item">
						<text class="label">身份证号</text>
						<text class="value">{{ userinfo.identity }}</text>
					</view>
				</view>
				<view class="qrcode-box" @click="previewQRCode">
					<view class="qrcode-wrapper">
						<tkiQrcode ref="qrcode" :val="qrCodeValue" :lv="1" :size="300" @result="qrR" mode="canvas" :options="{
							margin: 0,
							backgroundColor: '#ffffff',
							foregroundColor: '#000000'
						}"></tkiQrcode>
						<!-- <uv-qrcode
							ref="qrcode"
							:value="qrCodeValue"
							:size="140"
							mode="canvas"
							:options="{
								margin: 0,
								backgroundColor: '#ffffff',
								foregroundColor: '#000000'
							}"
							@complete="onQRCodeComplete"
							@error="onQRCodeError"
						></uv-qrcode> -->
					</view>
					<text>培训专属二维码</text>
					<text class="tip">点击放大</text>
				</view>
			</view>
		</view>
		<view class="project-list">
			<view class="project-card" v-for="(item, index) in data.chapterItems" :key="index">
				<view class="project-header">
					<text class="project-name">培训项目：{{ item.title }}</text>
					<text class="status-tag" :class="getStatusClass(item.status)">
						{{ getStatusText(item.status) }}
					</text>
				</view>
				<view class="project-info">
					<view class="info-row">
						<text class="label">培训老师</text>
						<view class="teacher-list">
							<view class="teacher-item" v-if="data.times?.[0]?.teachers && data.times?.[0]?.teachers.length" v-for="(teacher, tIndex) in data.times?.[0]?.teachers" :key="tIndex">
								<image class="teacher-avatar" :src="teacher.avatar" mode="aspectFill"></image>
								<text class="teacher-name">{{ teacher.name }}</text>
							</view>
							<text v-else class="value">--</text>
						</view>
					</view>
					<view class="info-row">
						<text class="label">审核时间</text>
						<text class="value">{{ parseTime(item.createDate) || '--' }}</text>
					</view>
					<view class="reject-reason" v-if="item.status === 2">
						<text class="label">不合格理由： {{ item.remark || '无' }}</text>
					</view>
				</view>
			</view>
		</view>
		<uv-notify ref="trainNotify" type="success"></uv-notify>
	</view>
</template>

<script>
import { getChapterDetailList } from '@/http/user'
import { parseTime } from '@/utils/tools'
import tkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue"
import WebSocketClient from '@/utils/webSocket.js'

export default {
	components: {
		tkiQrcode
	},
	data() {
		return {
			parseTime,
			qrCodeValue: '',
			trainNotifyMessage: '',
			data: {
				chapterItems: []
			},
			userinfo: {},
			trainingList: [
				{
					name: '安全用品',
					status: 0, // 0-未审核 1-合格 2-不合格
					teacher: '李老师',
					auditTime: '2024-01-01 9:00',
					rejectReason: ''
				},
				{
					name: '安全帽佩戴',
					status: 1,
					teacher: '张老师',
					auditTime: '2024-01-01 10:00'
				},
				{
					name: '安全带使用',
					status: 2,
					teacher: '王老师',
					auditTime: '2024-01-01 11:00',
					rejectReason: '安全带佩戴不规范，请重新学习后再次提交'
				}
			],
			qrCodeReady: false,
			qrImgUrl:'',
			chapterId:'', //科目id
			courseId:'' // 课程id
		}
	},
	onLoad(options) {
		this.chapterId = options.chapterId
		this.courseId = options.courseId
		this.userinfo = uni.getStorageSync('userinfo')
		this.initWebSocket()
		this.loadData()
	},
	onPullDownRefresh() {
		this.loadData()
	},
	methods: {
		handleNavigateToLocation(timeSlot) {
			if (!timeSlot || !timeSlot.location || typeof timeSlot.location !== 'string') {
                uni.showToast({
                    title: '位置信息无效',
                    icon: 'none'
                });
                return;
            }

            const parts = timeSlot.location.split(',');
            if (parts.length !== 2) {
                uni.showToast({
                    title: '位置坐标格式错误',
                    icon: 'none'
                });
                return;
            }

            const latitude = parseFloat(parts[0]);
            const longitude = parseFloat(parts[1]);

            if (isNaN(latitude) || isNaN(longitude)) {
                uni.showToast({
                    title: '无效的经纬度',
                    icon: 'none'
                });
                return;
            }

            uni.openLocation({
                latitude: latitude,
                longitude: longitude,
                name: timeSlot.address || '培训地点',
                address: timeSlot.address || '',
                success: function () {
                    console.log('打开地图成功');
                },
                fail: function (err) {
                    console.error('打开地图失败:', err);
                    uni.showToast({
                        title: '打开地图失败',
                        icon: 'none'
                    });
                }
            });
		},
		loadData() {
			getChapterDetailList({
				chapterId: this.chapterId
			}).then(res => {
				console.log(res.data)
				this.data = res.data
				if (this.data.times && Array.isArray(this.data.times)) {
                        this.data.times.sort((a, b) => {
                            const dateA = a.startTime ? new Date(a.startTime) : null;
                            const dateB = b.startTime ? new Date(b.startTime) : null;
                            const timeA = dateA && !isNaN(dateA.getTime()) ? dateA.getTime() : Infinity;
                            const timeB = dateB && !isNaN(dateB.getTime()) ? dateB.getTime() : Infinity;
                            if (timeA === Infinity && timeB === Infinity) return 0; // Keep original order for two invalid/missing times
                            return timeA - timeB;
                        });
                    }
				this.generateQRCode()
			}).finally(() => {
				uni.stopPullDownRefresh() // 停止下拉刷新动画
			})
		},
		generateQRCode() {
			const qrData = `http://student.qiananquang.com/#/pages/subject/subject?studentId=${this.data.student.id}&courseId=${this.courseId}&chapterId=${this.chapterId}`
			this.qrCodeValue = qrData
			this.$nextTick(() => {
				this.$refs.qrcode._makeCode()
			})
		},
		getStatusClass(status) {
			switch (status) {
				case 0: return 'status-pending'
				case 1: return 'status-pass'
				case 2: return 'status-reject'
				default: return ''
			}
		},
		getStatusText(status) {
			switch (status) {
				case 0: return '未审核'
				case 1: return '合格'
				case 2: return '不合格'
				default: return '--'
			}
		},
		qrR(val){
            this.qrImgUrl = val
        },
		previewQRCode() {
			uni.previewImage({
                urls: [this.qrImgUrl],
                success: () => {
                    console.log('预览成功')
                },
                fail: (err) => {
                    console.error('预览失败:', err)
                    uni.showToast({
                        title: '预览失败',
                        icon: 'none'
                    })
                }
            })
		},
		
		initWebSocket() {
			console.log('initWebSocket');
			this.wsClient = new WebSocketClient({
				url: 'wss://batapi.qiananquang.com:8222',
				heartbeatInterval: 30000,
				maxReconnectAttempts: 5
			})

			this.wsClient.onTokenInvalid(() => {

				console.error('Token失效，断开连接')

				uni.removeStorageSync('token')

				// setTimeout(() => {
				// 	uni.redirectTo({
				// 		url: '/pages/login/login'
				// 	})
				// }, 1500)
			})

			this.wsClient.onOpen(() => {
				console.log('WebSocket已连接')
				console.log(this.itemData, 'this.itemData');

			})

			this.wsClient.onMessage((res) => {
				try {
					const data = JSON.parse(res.data)
					if (data.code == 200) {
						if (data.data.type == 'check') {
							console.log(data.data, '监听消息');
							this.$nextTick(() => {
								// this.trainNotifyMessage = '恭喜你！' + data.data.title + '培训通过！'

								this.data.chapterItems.forEach(item => {
									if (item.itemId == data.data.itemId) {
										console.log('修改item');
										item.status = data.data.status
										item.remark = data.data.remark
									}
								})
								this.$refs.trainNotify.show({
									type: 'success',
									color: '#fff',
									message: '恭喜你！' + data.data.title + '培训通过！',
									duration: 1000 * 3,
									fontSize: '22rpx',
									safeAreaInsetTop: true
								})
								console.log(this.data, 'this.data.chapterItems');
								// this.$refs.lffBarrage.add({item:{nickname:'大橙子',courseName:'课程名称'}});
							})
						}
					}
				} catch (error) {
					console.error('解析消息失败:', error)
				}
			})

			this.wsClient.onError((error) => {
				console.error('WebSocket 错误:', error)
			})

			this.wsClient.onClose(() => {
				console.log('WebSocket 已关闭')
			})

			this.wsClient.connect()
		},
	}
}
</script>

<style lang="scss" scoped>
.training {
	padding: 30rpx;
	background: #e8e8e8;
	min-height: 100vh;

	.info-card {
		background: #FFFFFF;
		border-radius: 16rpx;

		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

		.course-info {
			border-bottom: 2rpx solid #EBEDF0;
			padding-bottom: 20rpx;
			background: #e4e4e473;

			.title {
				padding: 30rpx 30rpx 20rpx 30rpx;

				.course-name {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
					display: block;
				}

				.subject {
					font-size: 26rpx;
					color: #666;
					display: block;

				}
			}

			.time-box {
				display: flex;
				flex-direction: column;
				gap: 15rpx;
				padding: 0 30rpx;

				.time-box-item {
					.time-info-row {
						display: flex;
						align-items: center;
						margin-bottom: 5rpx;
					}
					.address-info-row {
						display: flex;
						align-items: center;
						.address-link {
							color: $uni-color-primary;
							text-decoration: underline;
						}
					}
					.label {
						font-size: 26rpx;
						color: #666;
						margin-right: 10rpx;
						min-width: 100rpx;
					}

					.value {
						font-size: 26rpx;
						color: #333;
					}
				}
			}
		}

		.user-info {
			display: flex;
			justify-content: space-between;
			flex-direction: column;
			padding: 30rpx;

			.student-info {
				flex: 1;
				padding-right: 30rpx;

				.info-item {
					margin-bottom: 8rpx;

					.avatar {
						width: 40rpx;
						height: 40rpx;
						border-radius: 50%;
						margin-right: 10rpx;
					}

					.label {
						font-size: 26rpx;
						color: #666;
						margin-right: 20rpx;
						display: inline-block;
					}

					.value {
						font-size: 26rpx;
						color: #333;
					}
				}
			}

			.qrcode-box {
				// width: 180rpx;
				text-align: center;
				flex-shrink: 0;

				.qrcode-wrapper {
					// width: 140rpx;
					// height: 140rpx;
					margin: 0 auto 10rpx;
					background: #fff;
					border-radius: 8rpx;
					overflow: hidden;
					display: flex;
					align-items: center;
					justify-content: center;

					// :deep(.uv-qrcode) {
					// 	width: 140rpx !important;
					// 	height: 140rpx !important;

					// 	canvas {
					// 		width: 140rpx !important;
					// 		height: 140rpx !important;
					// 	}
					// }
				}

				text {
					font-size: 24rpx;
					color: #666;
					display: block;
				}

				.tip {
					color: #0086FF;
					font-size: 22rpx;
					margin-top: 6rpx;
				}
			}
		}
	}

	.project-list {
		.project-card {
			background: #FFFFFF;
			border-radius: 16rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

			.project-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 20rpx;

				.project-name {
					font-size: 28rpx;
					font-weight: bold;
					color: #333;
					flex: 1;
				}

				.status-tag {
					padding: 4rpx 16rpx;
					border-radius: 24rpx;
					font-size: 24rpx;

					&.status-pending {
						background: #F5F6F8;
						color: #666;
					}

					&.status-pass {
						background: #E6F7FF;
						color: #0086FF;
					}

					&.status-reject {
						background: #FFF0F0;
						color: #FB4736;
					}
				}
			}

			.project-info {
				.info-row {
					display: flex;
					margin-bottom: 16rpx;

					.label {
						font-size: 26rpx;
						color: #666;
						width: 120rpx;
					}

					.teacher-list {
						flex: 1;
						display: flex;
						flex-wrap: wrap;
						gap: 16rpx;
						
						.teacher-item {
							display: flex;
							align-items: center;
							background: #F5F6F8;
							padding: 8rpx 16rpx;
							border-radius: 24rpx;
							
							.teacher-avatar {
								width: 32rpx;
								height: 32rpx;
								border-radius: 50%;
								margin-right: 8rpx;
							}
							
							.teacher-name {
								font-size: 24rpx;
								color: #333;
							}
						}
					}

					.value {
						font-size: 26rpx;
						color: #333;
						flex: 1;
					}
				}

				.reject-reason {
					background: #FFF0F0;
					border-radius: 8rpx;
					padding: 16rpx;
					margin-top: 16rpx;

					.label {
						font-size: 26rpx;
						color: #FB4736;
						margin-bottom: 8rpx;
						display: block;
					}

					.reason {
						font-size: 26rpx;
						color: #FB4736;
						line-height: 1.5;
					}
				}
			}
		}
	}
}
</style>
